#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 数据来源: https://github.com/selva86/datasets

import numpy as np 
import pandas as pd 
import matplotlib as mpl 
import matplotlib.pyplot as plt 
import seaborn as sns 
import warnings; warnings.filterwarnings(action='once')


# 1.3.4 抖动图(Jittering with stripplot)
# 多个数据点具有完全相同的X和Y值. 结果,多个点绘制会重叠并隐藏.
# 使用seaborn的stripplot()实现抖动。
"""
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")

# Draw Stripplot
fig, ax = plt.subplots(figsize=(16,10),dpi=80)
sns.stripplot(df.cty,df.hwy,jitter=0.25,size=8,ax=ax,linewidth=.5)

# Decorations
plt.title('Use jittered plots to avoid overlapping of points',fontsize=22)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\Jitteringstriplot.png")
plt.show()
"""


# 1.3.5 计数图(Counts Plot)
# 避免点重叠问题的另一个选择是增加点的大小,这取决于该点中有多少点.点的大小越大,其周围点的集中度越高.
"""
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")
df_counts = df.groupby(['hwy','cty']).size().reset_index(name='counts')

# Draw Stripplot
fig, ax = plt.subplots(figsize=(16,10),dpi=80)
sns.stripplot(df_counts.cty,df_counts.hwy,size=df_counts.counts*2,ax=ax)

# Decorations
plt.title('Counts Plot - Size of circle is bigger as more points overlap',fontsize=22)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\CountsPlot.png")
plt.show()
"""


# 1.3.6 边缘直方图(Marginal Histogram)
# 边缘直方图具有沿X和Y轴变量的直方图. 这用于可视化X和Y之间的关系以及单独的X和Y的单变量分布.
# 这种图经常用于探索性数据分析(EDA)
"""
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")

# Create Fig and gridspec
fig = plt.figure(figsize=(16,10),dpi=80)
grid = plt.GridSpec(4,4,hspace=0.5,wspace=0.2)

# Define the axes
ax_main = fig.add_subplot(grid[:-1,:-1])
ax_right = fig.add_subplot(grid[:-1,-1],xticklabels=[],yticklabels=[])
ax_bottom = fig.add_subplot(grid[-1,0:-1],xticklabels=[],yticklabels=[])

# Scatterplot on main ax
ax_main.scatter('displ','hwy',s=df.cty*4,c=df.manufacturer.astype('category').cat.codes,alpha=.9,data=df,cmap="tab10",edgecolors='gray',linewidths=.5)

# histogram on the right
ax_bottom.hist(df.displ,40,histtype='stepfilled',orientation='vertical',color='deeppink')
ax_bottom.invert_yaxis()

# histogram in the bottom
ax_right.hist(df.hwy,40,histtype='stepfilled',orientation='horizontal',color='deeppink')

# Decorations
ax_main.set(title='Scatterplot with Histograms \n displ vs hwy',xlabel='displ',ylabel='hwy')
ax_main.title.set_fontsize(20)
for item in ([ax_main.xaxis.label,ax_main.yaxis.label] + ax_main.get_xticklabels() + ax_main.get_yticklabels()):
    item.set_fontsize(14)

xlabels = ax_main.get_xticks().tolist()
ax_main.set_xticklabels(xlabels)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\MarginalHistogram.png")
plt.show()
"""



# 1.3.7 边缘箱形图(Marginal Boxplot)
# 箱线图有助于精确定位X和Y的中位数
"""
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")

# Create Fig and gridspec
fig = plt.figure(figsize=(16,10),dpi=80)
grid = plt.GridSpec(4,4,hspace=0.5,wspace=0.2)

# Define the axes
ax_main = fig.add_subplot(grid[:-1,:-1])
ax_right = fig.add_subplot(grid[:-1,-1],xticklabels=[],yticklabels=[])
ax_bottom = fig.add_subplot(grid[-1,0:-1],xticklabels=[],yticklabels=[])

# Scatterplot on main ax
ax_main.scatter('displ','hwy',s=df.cty*5,c=df.manufacturer.astype('category').cat.codes,alpha=.9,data=df,cmap="Set1",edgecolors='black',linewidths=.5)

# Add a graph in each part
sns.boxplot(df.hwy,ax=ax_right,orient="v")
sns.boxplot(df.displ,ax=ax_bottom,orient="h")

# Decorations ----------
# Remove x axis name for the boxplot
ax_bottom.set(xlabel='')
ax_right.set(ylabel='')

# Main Title,Xlabel and Ylabel
ax_main.set(title='Scatterplot with Histograms \n displ vs hwy',xlabel='displ',ylabel='hwy')

# Set font size of different components
ax_main.title.set_fontsize(20)
for item in ([ax_main.xaxis.label,ax_main.yaxis.label] + ax_main.get_xticklabels() + ax_main.get_yticklabels()):
    item.set_fontsize(14)

plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\MarginalBoxplot.png")
plt.show()
"""




# 1.3.8 相关图(Correllogram)
# 相关图用于直观地查看给定数据框(或二维数组)中所有可能的数值变量对之间的相关度量.
"""
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mtcars.csv")

# Plot
plt.figure(figsize=(12,10),dpi=80)
sns.heatmap(df.corr(),xticklabels=df.corr().columns,yticklabels=df.corr().columns,cmap='RdYlGn',center=0,annot=True)

# Decorations
plt.title('Correlogram of mtcars',fontsize=22)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\Correllogram.png")
plt.show()
"""




# 1.3.9 矩阵图(PairwisePlot)
# 矩阵图是探索性分析中的最爱,用于理解所有可能的数值变量对之间的关系. 它是双变量分析的必备工具.
"""
df = sns.load_dataset('iris')
# Plot
plt.figure(figsize=(10,8),dpi= 80)
sns.pairplot(df,kind="scatter",hue="species",plot_kws=dict(s=80,edgecolor="white",linewidth=2.5))
plt.show()

df = sns.load_dataset('irir')
# Plot
plt.figure(figsize=(10,8),dpi=80)
sns.pairplot(df,kind="red",hue="species")
plt.show()

'''
输出结果报错:
urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed>
The terminal process terminated with exit code: 1
'''
"""
